#!/bin/bash

# 设置软件安装目录
conda_dir="$HOME/.labelapp/miniconda"
node_dir="$HOME/.labelapp/nodejs"
labelapp_dir="$HOME/.labelapp/labelapp"
root_dir="$HOME/.labelapp"

# 获取 Python 目录，过滤掉 miniconda
python_dir=$(env PATH="$(echo $PATH | tr ':' '\n' | grep -v 'miniconda' | tr '\n' ':')" which python3 2>/dev/null)

# 获取 conda 版本
conda_version=$(eval "$conda_dir/bin/conda --version" 2>/dev/null)
conda_version=$(echo "$conda_version" | sed "s/^conda\s*//")

# 获取 node 版本
node_version=$(eval "$node_dir/bin/node -v" 2>/dev/null)
node_version=$(echo "$node_version" | sed "s/^v//")

# 获取 python 版本
python_version=$(eval "env PATH=\"$(echo $PATH | tr ':' '\n' | grep -v 'miniconda' | tr '\n' ':')\" python3 --version" 2>/dev/null)
python_version=$(echo "$python_version" | sed "s/^Python\s*//")

# 获取 labelapp 版本
labelapp_version=$(eval "cat $root_dir/VERSION" 2>/dev/null)
labelapp_version=$(echo "$labelapp_version" | sed "s/^\s*//")

# Function to format software entry
format_software_entry() {
  local name="$1"
  local version="$2"
  local directory="$3"
  if [[ "$version" == "" ]]; then
    echo "\"$name\": null"
  else
    echo "\"$name\": {
      \"version\": \"$version\",
      \"directory\": \"$directory\"
    }"
  fi
}

# Format each software entry
conda_entry=$(format_software_entry "conda" "$conda_version" "$conda_dir")
node_entry=$(format_software_entry "node" "$node_version" "$node_dir")
python_entry=$(format_software_entry "python" "$python_version" "${python_dir:-null}")
labelapp_entry=$(format_software_entry "labelapp" "$labelapp_version" "$labelapp_dir")

# 构建JSON输出
json_output=$(cat <<EOF
{
    $conda_entry,
    $node_entry,
    $python_entry,
    $labelapp_entry
}
EOF
)

# 输出JSON结果
echo "$json_output"